const initialState = {
  list: [
    { id: 1, task: 'React', isDone: false },
    { id: 2, task: 'Vue', isDone: true },
    { id: 3, task: 'TS', isDone: true },
  ],
  type: 'all',
};

export type TaskType = {
  id: number;
  task: string;
  isDone: boolean;
};

export type ActionType =
  | {
      type: 'todo/updateById';
      payload: number;
    }
  | { type: 'todo/clearDone' }
  //  3. 扩展ActionType的类型
  | { type: 'todo/add'; payload: TaskType };

// 💥reducer函数中不要解构action对象
// 💥reducer函数必须指定返回值类型
export default function todoReducer(state = initialState, action: ActionType): typeof initialState {
  switch (action.type) {
    case 'todo/updateById':
      return {
        ...state,
        list: state.list.map((item) => {
          return { ...item, isDone: item.id === action.payload ? !item.isDone : item.isDone };
        }),
      };

    case 'todo/clearDone':
      return {
        ...state,
        list: state.list.filter((item) => !item.isDone),
      };

    // * 6. 完成新增的计算
    case 'todo/add':
      return {
        ...state,
        list: [action.payload, ...state.list],
      };

    default:
      return state;
  }
}
